package com.bridgeintelligent.tag.customer.service;

import com.alibaba.fastjson.JSON;
import com.bridgeintelligent.tag.constants.TagConstants;
import com.bridgeintelligent.tag.customer.entity.CustomersPage;
import com.bridgeintelligent.tag.customer.entity.Issue;
import com.bridgeintelligent.tag.customer.entity.IssueTask;
import com.bridgeintelligent.tag.customer.mapper.IssueMapper;
import com.bridgeintelligent.tag.customer.mapper.IssueTaskMapper;
import com.bridgeintelligent.tag.customer.model.IssueModel;
import com.bridgeintelligent.tag.customer.vo.IssueTaskVO;
import com.bridgeintelligent.tag.customer.vo.IssueVO;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.bridgeintelligent.tag.webserver.workflow.ApproverService;
import com.bridgeintelligent.tag.webserver.workflow.Instance;
import com.bridgeintelligent.tag.webserver.workflow.SubmitterService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @description
 * @author: grp 2021-02-24 14:15
 **/
@Service
@Slf4j
@AllArgsConstructor
public class IssueApproveServiceImpl implements IIssueApproveService {

    private final IssueTaskMapper issueTaskMapper;
    final private SubmitterService submitterService;
    final private IssueMapper issueMapper;
    final private ICustomerApprovalService customerApprovalService;
    final private ApproverService approverService;

    final private IIssueTaskService issueTaskService;

    @Override
    public void reject(String customersId, String applicant, String instanceId, String desc) {
        Instance reject = approverService.reject(instanceId, desc);
        User user = TagSecurityHelper.currentUser();
        //删除客群相关信息
        Issue issue = issueMapper.findByInstanceId(instanceId);
        issueMapper.updateApproveInfo(issue.setApproveStatus("3")
                .setApproverId(user.getUserId()).setApproveTime(new Date()));
    }

    @Override
    public boolean checkExportSetting(IssueModel issue) {
        return false;
    }

    @Override
    public String addCommit(IssueModel issue) {
        Instance instance = submitterService.submit(new SubmitterService.SubmitParam().setResourceId(issue.getId())
                .setWorkflowId(TagConstants.Workflow.ID_10016));
        Issue info = new Issue();
        // 待审核
        issueMapper.updateApproveInfo(info.setId(issue.getId()).setInstanceId(instance.getId()).setApproveStatus("2"));
        return instance.getId();
    }

    @Override
    public String resubmit(String id){
        IssueVO issue = issueMapper.findOne(id);
        Instance submit = submitterService.submit(new SubmitterService.SubmitParam().setInstanceId(issue.getInstanceId())
                .setResourceId(issue.getId())
                .setWorkflowId(TagConstants.Workflow.ID_10016));
        //修改数据状态为待审核
        Issue info = new Issue();
        issueMapper.updateApproveInfo(info.setId(issue.getId()).setInstanceId(issue.getInstanceId()).setApproveStatus("2"));
        //重新走审批后，任务管理的数据应该删除掉，在审批通过的时候再重新插入
        IssueTaskVO dbTask = issueTaskMapper.findOne(issue.getId());
        if (dbTask != null){
            issueTaskMapper.deleteById(issue.getId());
        }
        return submit.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPass(String customerId, String instanceId, String applicant) {
        Instance pass = approverService.pass(instanceId);
        User user = TagSecurityHelper.currentUser();
        //删除客群相关信息
        Issue issue = issueMapper.findByInstanceId(instanceId);
        issueMapper.updateApproveInfo(issue.setApproveStatus("4")
                .setApproverId(user.getUserId()).setApproveTime(new Date()).setState("01"));
        try{
            IssueVO issueVO = issueMapper.findOne(issue.getId());
            IssueTask task = new IssueTask();
            BeanUtils.copyProperties(issueVO,task);
            task.setIsDel("00");
            issueTaskMapper.add(task);
            //立即下发模式直接触发MQ动作
            if ("1".equals(task.getFrequency())){
                issueTaskService.immediateTask(task);
            }
            //此处针对编辑的审批通过，如果是每月下发模式或者每周下发模式，将同步修改日志表的数据
            if("4".equals(task.getFrequency()) || "3".equals(task.getFrequency())){
                synchData(task);
            }
        }catch (Exception e){
            log.error("下发任务创建失败",e);
        }
    }

    @Override
    public CustomersPage<IssueVO> findList(Integer pageNumber, Integer pageSize, String customerName, String approveType, String approveState, String uptTimeStart, String uptTimeEnd) {
        //获取权限id
        List<String> workflowIds = customerApprovalService.findInstanceByPower(approveType);
        if (CollectionUtils.isEmpty(workflowIds)) {
            workflowIds.add(IDGenerator.gen());
        }
        Map map = new HashMap();
        map.put("customerName", customerName);
        map.put("approveState", approveState);
        map.put("uptTimeStart", uptTimeStart);
        if (uptTimeEnd != null && !"".equals(uptTimeEnd)) {
            map.put("uptTimeEnd", uptTimeEnd + "23.59.59");
        }
        map.put("workflowIds", workflowIds);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -2);
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<IssueVO> list = issueMapper.findCusApproveList(map);
        if (CollectionUtils.isNotEmpty(list)) {
            for (IssueVO issueVO : list) {
                if (issueVO.getUpdateTime()!=null&&calendar.getTime().compareTo(issueVO.getUpdateTime()) < 1) {
                    issueVO.setIsnew(true);
                } else {
                    issueVO.setIsnew(false);
                }
            }
        }
        CustomersPage<IssueVO> customersPage = new CustomersPage<>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(pageNumber);
        return customersPage;
    }


    public void synchData(IssueTask task){
        String taskId = task.getId();
        log.info("task:{}",task);
        //通过taskId查询出所有taskLog数据
        List<String> logIds = issueTaskMapper.findLogByIssueId(taskId);
        log.info("logIds:{}", JSON.toJSONString(logIds));
        logIds.forEach(id ->{
            task.setId(id);
            log.info("task:{}",JSON.toJSONString(task));
            issueTaskMapper.updateTaskLog(task);
        });
    }

}
